<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: edit_form_jl_import.tpl.php 1150 2008-06-24 14:33:03Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
 */ 

?>

<div id="right">
	<div id="rightpad">
	
<!-- Header START -->	
		<div id="step">
			<div class="t">
        <div class="t">
          <div class="t"></div>
        </div>
      </div>
      <div class="m" align="left">
				<div class="far-right">
							<div class="button1-left"><div class="help"><a href="http://www.joomleague.de" title="<?php echo _JL_ADMIN_MANUAL;?>" target="blank"><?php echo _JL_ADMIN_MANUAL;?></a></div></div>
							<div class="button1-left"><div class="forum"><a href="http://www.joomleague.de/forum/" title="<?php echo _JL_ADMIN_FORUM;?>" target="blank"><?php echo _JL_ADMIN_FORUM;?></a></div></div>
							<div class="button1-left"><div class="about"><a href="http://www.joomleague.de" title="<?php echo _JL_ADMIN_INFO;?>" target="blank"><?php echo _JL_ADMIN_INFO;?></a></div></div>
				</div>
				<div class="button1-left"><div class="blank"><a href="index2.php?option=com_joomleague"></a></div></div><span class="step"><?php echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_JL;?></span>
			</div>
      <div class="b">
        <div class="b">
          <div class="b"></div>
        </div>
      </div>
    </div>
<!-- Header END -->	

    <div id="installer">
    
<!-- Title 1 START -->  
			<div class="t">
        <div class="t">
          <div class="t"></div>
        </div>
      </div>
      <div class="m" align="left">
      	<h2><?php echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_TITLE;?></h2>		
<!-- Title 1 END -->        		 
  
<!-- Info 1 START -->  			
		<div id="step">
			<div class="t">
        <div class="t">
          <div class="t"></div>
        </div>
      </div>
      <div class="m" align="left">
<table class="content" cellpadding="4">
 <tr>
  <td><?php echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_HINT1;?>
  </td>
 </tr>
</table>
			</div>
      <div class="b">
        <div class="b">
          <div class="b"></div>
        </div>
      </div>
    </div>
<!-- Info 1 END -->    
  	
<!-- Content START -->				
				<div class="install-text2">
	<table cellpadding="4" cellspacing="0" border="0" width="100%" class="adminlist2">



<!-- ab hier startet LMO Import -->			
			

<?php

$sent = mosGetParam($_REQUEST , 'sent' ,'');

if(!$sent)
{
	?>
	<div style='text-align: center;'>
	<form action="<?php echo JL_ADMIN_COMPONENT_LINK;?>&act=JLimport" method="post" enctype="multipart/form-data">
	<input type="hidden" name="sent" value="1">
	<p><?php echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_CHOOSE_YOUR_FILE; ?>
	<input type="file" name="file"></p>
	<p><input type="submit" value="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_NEXT; ?>"></p>
	</form>
	</div>
	<?php
}	
if ($sent)
{
	$korrekt = 1;
	$tempfile = $_FILES['file']['tmp_name'];
	$type = substr($_FILES['file']['name'], -3);
	// changed by Gucky 2007/02/19 removed auto-create $_POSTS sent to 2nd part
  
  if ($sent==1) {
  	if ($type != "jlg")
  	{
  		echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_ONLY_JLG_FILES;
  		$korrekt = 0;
  		//echo "<br>".$type;
  	}
  	else
  	{
      if (file_exists( _JOOMLA_JL_PATH."/images/stories/jlFile.jl" )) {
        unlink(_JOOMLA_JL_PATH."/images/stories/jlFile.jl");
      }
      if (!move_uploaded_file($tempfile, _JOOMLA_JL_PATH."/images/stories/jlFile.jl")) 
    	{
    		echo _JL_ADMIN_JLIMPORT_UPLOAD_PROBLEM;
    		$korrekt = 0;
    	}
  	}
  }
	if ($korrekt)
	{
    $file = _JOOMLA_JL_PATH."/images/stories/jlFile.jl";

		/*
    * first, parsing of the file
    */
    $xml = new XmlImport();
    $objects = $xml->parse($file, substr(_ISO,8) );
    // $mainframe->setUserState( 'jlgimport', $objects );
    unset($xml);
    //print_r($objects);exit;
    
    /* create shortcuts... */
    if (array_key_exists('joomleague',$objects)) $proj      =& $objects['joomleague'][0];
    if (array_key_exists('teamtool',$objects))   $teamtools =& $objects['teamtool'];
    if (array_key_exists('jl_team',$objects))    $teams     =& $objects['jl_team'];
    if (array_key_exists('club',$objects))       $clubs     =& $objects['club'];
    if (array_key_exists('round',$objects))      $rounds    =& $objects['round'];
    if (array_key_exists('match',$objects))      $matches   =& $objects['match'];
    if (array_key_exists('leaguedivision',$objects)) $divisions =& $objects['leaguedivision'];   
    
    //print_r($divisions);  exit();  
}

if ($sent == 1)
{         
		if ($proj->name){
		  echo '<pre>';
      echo '<img align="top" src="components/com_joomleague/images/ok.png" alt="'._JL_OK.'" title"'._JL_OK.'">';
      echo '&nbsp;'; 
      echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_FILE_MESSAGE1;
      
      // changed by Gucky 2007/02/19 changed to original filename
      echo "<b>".$_FILES['file']['name']."</b>";
      // changed by Gucky 2007/02/19 changed to original filename ends
      echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_FILE_MESSAGE2;
      echo '</pre><br />'._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATE_CLUBS_HINT;

      $query="SELECT COUNT(*) FROM #__joomleague_teams";
			$database->setQuery($query);
			$countteams = $database->loadResult();
			$query="SELECT COUNT(*) FROM #__joomleague_clubs";
			$database->setQuery($query);
			$countclubs = $database->loadResult();
		}
		else {
			echo "<br />"._JL_ADMIN_EDIT_LIST_JL_ERROR_FILE_READ;
			exit;
		}
		echo "</pre>";
		?>
<script type="text/javascript">
function chkFormular () {
	var message="";
  if (document.adminForm.name.value == "") {
    message+="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_PLEASE_NAME;?>\n";
  }
  if ((document.adminForm.season.selectedIndex == "0")&&(document.adminForm.seasonNew.value == "")) {
    message+="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_NO_SEASON;?>\n";
  }
    if ((document.adminForm.league.selectedIndex == "0")&&(document.adminForm.leagueNew.value == "")) {
    message+="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_NO_LEAGUE;?>\n";
  }
  if (document.adminForm.admin.selectedIndex == "0") {
    message+="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_ADMIN;?>\n";
  }
  if (document.adminForm.editor.selectedIndex == "0") {
    message+="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_EDITOR;?>\n";
  }
<?php
for ($counter=0;$counter<count($teams);$counter++)
{
?>
	if ((document.adminForm.chooseteam_<?php echo $counter; ?>.selectedIndex == "0")&&(document.adminForm.teamname_<?php echo $counter; ?>.disabled == true)) {
  message+='<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_TEAM_CONFIG_MISSING." ".addslashes($teams[$counter]->name);?>\n';
	}
	
	if ((document.adminForm.chooseclub_<?php echo $counter; ?>.selectedIndex == "0")&&(document.adminForm.clubname_<?php echo $counter; ?>.disabled == true)) {
  message+='<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CLUB_CONFIG_MISSING." ".addslashes($teams[$counter]->name);?>\n';
	}
<?php
}

?>
  if (message=="") return true;
  else {
  	alert("<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_ERROR;?>\n\n"+message);
  	return false;
  }
  
  alert("test");
}

function checkAllCustom( n, fldName ) {
  if (!fldName) {
     fldName = 'cb';
  }
	var f = document.adminForm;
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) {
		cb = eval( 'f.' + fldName + '' + i );
		if (cb) {
			cb.checked = c;
			test(cb,cb.value);
			n2++;
		}
	}
	if (c) {
		document.adminForm.boxchecked.value = n2;
	} else {
		document.adminForm.boxchecked.value = 0;
	}
}
  	function test( box, id)
  	{
  		if(box.checked)
  		{
  			eval("document.adminForm.chooseteam_"+id+".disabled=true");
  			eval("document.adminForm.teamname_"+id+".disabled=false");
  			eval("document.adminForm.teamshort_"+id+".disabled=false");
  			eval("document.adminForm.sctclub_"+id+".disabled=false");
  			eval("document.adminForm.sctclub_"+id+".checked=true");
  			eval("document.adminForm.chooseclub_"+id+".disabled=true");
  			eval("document.adminForm.clubname_"+id+".disabled=false");
        eval("document.adminForm.clubid_"+id+".disabled=false");
  		}
  		else
  		{
  			eval("document.adminForm.chooseteam_"+id+".disabled=false");
  			eval("document.adminForm.teamname_"+id+".disabled=true");
  			eval("document.adminForm.teamshort_"+id+".disabled=true");
  			eval("document.adminForm.sctclub_"+id+".disabled=true");
  			eval("document.adminForm.sctclub_"+id+".checked=false");
  			eval("document.adminForm.chooseclub_"+id+".disabled=false");
  			eval("document.adminForm.clubname_"+id+".disabled=true");
        eval("document.adminForm.clubid_"+id+".disabled=true");
  		}
  	}
</script>		
		<table border="0"><tr><td colspan='2'>
		<form name='adminForm' action='<?php echo JL_ADMIN_COMPONENT_LINK;?>&act=JLimport' method='post' onsubmit='return chkFormular()'>
		<input type='hidden' name='sent' value='2' id='sent'>
<input type="hidden" name="boxchecked" value="0" />
		
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_NAME_OF_PROJECT; ?></td>
		<td><input type='text' name='name' id='name' value="<?php echo $proj->name;?>"></td></tr>
		
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_LEAGUE; ?></td>
		<td>
		<?php
		$query = "SELECT name, id FROM #__joomleague_leagues ORDER BY name";

		$database->setQuery($query);
		$rows = $database->loadObjectList();
		if (count($rows)>0)
		{ ?>
			<select name='league' id='league'>
		<option><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_LEAGUE; ?></option>
		<?php
			foreach ($rows AS $row)
			{
				echo "<option value='". $row->id ."'>". $row->name ."</option>\n";
			}
			echo "</select>"; ?>
		<input type="checkbox" name="newLeagueCheck" value="1"
		onclick="if(this.checked){document.adminForm.league.disabled=true;document.adminForm.leagueNew.disabled=false;document.adminForm.leagueNew.value=document.adminForm.name.value} 
		else {document.adminForm.league.disabled=false;document.adminForm.leagueNew.disabled=true}"><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATE;?>
		<input type="text" name="leagueNew" id='leagueNew' disabled>
		<?php
		}
		else {
    ?>
			<input type="hidden" name="newLeagueCheck" value="1"><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATE;?>
		<input type="text" mosReq="1" name="leagueNew" id='leagueNew' value="<?php echo $proj->name;?>">
		<?php
    }
		?>
		
			</td></tr>

		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_SEASON; ?></td>
		<td>
		<?php
		$query = "SELECT name, id FROM #__joomleague_seasons ORDER BY name";
		$database->setQuery($query);
		$rows = $database->loadObjectList();
		if (count($rows)>0)	{ 
      ?>
			<select name='season' id='season'>
  		<option selected value="0"><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_SEASON; ?></option>
  		<?php
  		foreach ($rows AS $row)
  		{
  			echo "<option value='". $row->id ."'>". $row->name ."</option>\n";
  		}
  		echo "</select>"; ?>
  		<input type="checkbox" name="newSeasonCheck" value="1"
  		onclick="if(this.checked){document.adminForm.season.disabled=true;document.adminForm.seasonNew.disabled=false} 
  		else {document.adminForm.season.disabled=false;document.adminForm.seasonNew.disabled=true}"><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATE;?>
  		<input type="text" name="seasonNew" id='seasonNew' disabled>
  		<?php
  	}
		else {
      ?>
			<input type="hidden" name="newSeasonCheck" value="1"/><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATE;?>
		  <input type="text" name="seasonNew" id='seasonNew' value="<?php echo $proj->name;?>"/>
		  <?php
    }
		?>
		</td></tr>
		<!--Ligaadmin w�hlen -->
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_ADMIN; ?></td>
		<td><select name='admin' id='admin'>
		<option></option>
		<?php
		// changed by Gucky 2007/02/19 added WHERE clause for at least admin only
		$query = "SELECT username, id, usertype FROM #__users WHERE usertype = 'Super Administrator' OR usertype = 'Administrator' ORDER BY username";
		// changed by Gucky 2007/02/19 added WHERE clause ends
		$database->setQuery($query);
		$rows = $database->loadObjectList();
		foreach ($rows AS $row) {
			echo "<option value='". $row->id ."'>". $row->username ."</option>\n";
		}
		
		?> 
		</select></td></tr>
		
		<!--Ligaeditor w�hlen -->
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHOOSE_EDITOR; ?></td>
		<td><select name='editor' id='editor'>
		<option></option>
		<?php
		$query = "SELECT name, id FROM #__users ORDER BY name";
		$database->setQuery($query);
		$rows = $database->loadObjectList();
		foreach ($rows AS $row)
		{
			echo "<option value='". $row->id ."'>". $row->name ."</option>\n";
		}
		?> 
		</select></td></tr>
		
		<!--import existing project settings -->
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_USE_PROJECT_TEMPLATE; ?></td>
		<td><select name='copyTemplate' id='copyTemplate'>
		<option value="0" selected>New templates</option>
		<?php
		$query = "SELECT name, id FROM #__joomleague ORDER BY name";
		$database->setQuery($query);
		$rows = $database->loadObjectList();
		foreach ($rows AS $row)
		{
			echo "<option value='". $row->id ."'>". $row->name ."</option>\n";
		}
		?> 
		</select></td></tr>
		
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CURRENT_ROUND; ?></td><td><input type="text" name="aktspieltag" value="<?php echo $proj->current_round; ?>"></td></tr>
		
		<!--Project ver�ffentlichen-->
		<tr><td><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_PUBLISH_PROJECT; ?></td>
		<td>
		<input type="radio" name="publish" value="0"  checked="checked"> <?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_NO; ?>
		<input type="radio" name="publish" value="1"> <?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_YES; ?>
		</td></tr>
		
		<tr><td><br /></td></tr>
    
    <tr><td><b><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_TEAM_CLUB_ASSIGN ?></b></td></tr>
    <script>
    
  	</script>

    <?php //exit; ?>

    <table cellpadding="4" cellspacing="0" border="0" width="100%" class="adminlist2">
  	<thead>
      <tr>
      	<th nowrap><input type="checkbox" name="toggle" value="" onclick="checkAllCustom(<?php echo count( $teams ); ?> )" /><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_ALL_NEW; ?></th>
				<th width="30%"><?php echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_JL_TEAM;?></th>
				<th width="10%">&nbsp;</th>
        <th width="30%"><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_JL_TEAM;?></th>
   
				<th width="10%"></th>
        <th width="30%"><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_JL_CLUB;?></th>
			</tr>
  	</thead>
  	
		<?php
		$color1 = "#DDDDDD";
		$color2 = "#EEEEEE";
		$i=0;
		foreach ($teams AS $key => $team)
		{
			if ($key%2 == 1) $color = $color1;
			else $color = $color2;
				
			$create = 1;
			echo "<tr><td style='text-align:left; valign:center;background:$color' colspan='2'><b>$team->name</b>:<br>";
			if ($countteams>0)
			{
				echo "<input type=\"checkbox\" value=\"$key\" name=\"cid[]\" value=\"\" id=\"cb$i\" onchange=\"test(this,$key)\"><b>"._JL_ADMIN_EDIT_LIST_LMO_IMPORT_TEAM_CREATE_NEW;
			}
			else
			{
				echo "<b>"._JL_ADMIN_EDIT_LIST_LMO_IMPORT_NO_TEAM_YET."</b>";
			}
			echo "<td style='text-align:center; valign:center;background:$color'>-></td>";
			
			echo "<td style=\"background:$color\">";
			if ($countteams>0)
			{
				echo "<select name=\"chooseteam_$key\" onchange=\"
          if(this.options[this.selectedIndex.value]!='') { 
            document.adminForm.chooseclub_$key.disabled=true;
            document.adminForm.sctclub_$key.disabled=true;
          } 
          else { 
            document.adminForm.sctclub_$key.disabled=false; 
            document.adminForm.chooseclub_$key.disabled=false
          }
          \">\n";
				echo "<option value=\"0\">"._JL_ADMIN_EDIT_LIST_JL_IMPORT_SELECT_TEAM."</option>\n"; 
				
				$query="SELECT name, id, club_id FROM #__joomleague_teams ORDER BY name";
				$database->setQuery($query);
				$rows = $database->loadObjectList();
				
				$foundMatchingTeam = 0;
				$matchingTeam_clubid = 0;
				foreach ($rows AS $row)
				{	
					echo "<option ";
				  // Wenne es bereits ein Team mit gleichen Namen gibt --> selectiere es gleich
					if ($row->name == $team->name) 
					{
						echo "selected ";
            $foundMatchingTeam = $row->id;
            $matchingTeam_clubid = $row->club_id; 
						$create = 0;	
					}					 
					echo "value='". $row->id ."'>". $row->name ."</option>\n";
				}
				echo "</select>";
		

				echo "<table cellspacing='0' cellpadding='0'><tr><td>"._JL_ADMIN_EDIT_LIST_TEAMS_TEAM."</td><td>"._JL_ADMIN_EDIT_LIST_TEAMS_SHORTNAME."</td></tr><tr><td><input type='text' name='teamname_$key' value='$team->name' disabled></td><td><input type='text' name='teamshort_$key' maxlength='3' size='5' value='$team->short_name' disabled></td></tr></table>";
			}
			else
			{
				echo "<table cellspacing='0' cellpadding='0'><tr><td>"._JL_ADMIN_EDIT_LIST_TEAMS_TEAM."</td><td>"._JL_ADMIN_EDIT_LIST_TEAMS_SHORTNAME."</td></tr><tr><td><input type='text' name='teamname_$key' value='$team->name'></td><td><input type='text' name='teamshort_$key' maxlength='3' size='5' value='$team->short_name'></td></tr></table>";
			}
			echo "</td>";
			echo "<td style='text-align:center; valign:center;background:$color'>-></td>";
			
      //look for corresponding club in imported data
			$clubname='';
      $clubid=0;
      foreach($clubs as $club) {
        if ( $club->id == $team->club_id ) {
          $clubname=$club->name;
          $clubid=$club->id;
          break; //only one match possible...
        }          
      }
      
      //Clubs auswahl anzeigen
			$create = 1;
			
      echo "<td style='text-align:right; valign:center;background:$color'>";
      if ($countclubs>0)
			{
      	if ($matchingTeam_clubid) echo "<select name='chooseclub_$key' disabled>";
      	else echo "<select name='chooseclub_$key'>";
      	
				$query="SELECT name, id FROM #__joomleague_clubs ORDER BY name";
				echo "<option>"._JL_ADMIN_EDIT_LIST_JL_IMPORT_SELECT_CLUB."</option>\n"; 
			
				$database->setQuery($query);
				$rows = $database->loadObjectList();
			
				foreach ($rows AS $row)
				{	
					echo "<option ";
				  // find a corresponding club
					if ($matchingTeam_clubid) {
            if ($matchingTeam_clubid == $row->id)
  					{
  						echo "selected "; 
  						$create = 0;	
  					}					
          }
          else {
            if ($clubname == $row->name)
  					{
  						echo "selected "; 
  						$create = 0;	
  					}
          }					 
					echo "value='". $row->id ."'>". $row->name ."</option>\n";
				}	

  			echo "</select><br>";
			}
			else
			{				
        echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_NO_CLUB_YET."<br><input type='text' name='clubname_$key' value=''>";
			}
			echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_OR_CREATE_NEW.": 
        <input type='checkbox' name='sctclub_$key' 
          onclick='if(this.checked){
          document.adminForm.chooseclub_$key.disabled=true;
          document.adminForm.clubname_$key.disabled=false;
          document.adminForm.clubid_$key.disabled=false;
          }	
          else {
          document.adminForm.chooseclub_$key.disabled=false;
          document.adminForm.clubname_$key.disabled=true;
          document.adminForm.clubid_$key.disabled=true;
          }'";
        if ($matchingTeam_clubid) echo " disabled>";
        else echo " >";
			echo "<br><input type='text' name='clubname_$key' value='$clubname' disabled><input type='hidden' name='clubid_$key' value='$clubid' disabled>";
			echo "</td></tr>";
			$i++;
			
		}
		
		?>
		</table>
		
		<tr><td colspan="2"><input type="submit" value="<?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_START;?>"></td></tr>
		
		</form>
		</table>

		<?php
	}

}
if ($sent == 2)
{	
  //print_r($_POST);exit;
	$assignedteams=array();
	$newteams=array();
	$newteamsshort=array();
	$assignedclubs=array();
	$newclubs=array();
	$newclubsid=array();
	
	//tracking of old -> new ids
	$convertClubID=array();
  $convertTeamID=array();
	$convertRoundID=array();
	$convertDivisionID=array();
	
  foreach($_POST as $key => $element)
	{
		if (substr($key,0,10)=="chooseteam")
		{
			//the team from the file is replaced with an existing team
      $tempteams=explode ("_",$key);
			$assignedteams[$tempteams[1]]=$element;
		}
		elseif (substr($key,0,8)=="teamname")
		{
			$tempteams=explode ("_",$key);
			$newteams[$tempteams[1]]=$element;
		}
		elseif (substr($key,0,9)=="teamshort")
		{
			$tempteams=explode ("_",$key);
			$newteamsshort[$tempteams[1]]=$element;
		}
		elseif (substr($key,0,10)=="chooseclub")
		{
			$tempteams=explode ("_",$key);
			$assignedclubs[$tempteams[1]]=$element;
		}
		elseif (substr($key,0,8)=="clubname")
		{
			$tempteams=explode ("_",$key);
			$newclubs[$tempteams[1]]=$element;
		}
		elseif (substr($key,0,6)=="clubid")
		{
			$tempteams=explode ("_",$key);
			$newclubsid[$tempteams[1]]=$element;
		}
	}
  //print_r($newclubsid);exit;

	if (isset($_POST["name"])) $proj->set( 'name', $_POST["name"] );
	if (isset($_POST["league"])) $proj->set( 'league_id', $_POST["league"] );
  else $proj->set( 'league_id', '' );
	if (isset($_POST["season"])) $proj->set( 'season_id', $_POST["season"] );
  else $proj->set( 'season_id', '' );
	if (isset($_POST["admin"])) $proj->set( 'joomleague_admin', $_POST["admin"] );
	if (isset($_POST["editor"])) $proj->set( 'joomleague_editor', $_POST["editor"] );
	if (isset($_POST["aktspieltag"])) $proj->set( 'current_round', $_POST["aktspieltag"] );

	if (isset($_POST["publish"])) $proj->set( 'published', $_POST["publish"] );

	if (isset($_POST["newLeagueCheck"])) $newLeagueCheck = $_POST["newLeagueCheck"]; else $newLeagueCheck=0;
	if (isset($_POST["newSeasonCheck"])) $newSeasonCheck = $_POST["newSeasonCheck"]; else $newSeasonCheck=0;

	$korrekt = 1;
	
	if (!$proj->name || (!$proj->league_id&&!$_POST["leagueNew"]) || (!$proj->season_id&&!$_POST["seasonNew"]) || !$proj->joomleague_admin || !$proj->joomleague_editor)
	// changed by Gucky 2007/02/19 added $_POST_Vars ends
	{
		?><p><?php echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_CHECK_REQUIRED;?></p><?php
		$korrekt = 0;
		exit;
	}		
       	
	$query = "SELECT * FROM #__joomleague 
				WHERE name = '$proj->name'
				AND league_id = '$proj->league_id'
				AND season_id = '$proj->season_id'";
	$database->setQuery($query);
	$database->query($query);
	$num = $database->getAffectedRows();
	if ($num>0) {
		echo "<p>"._JL_ADMIN_EDIT_LIST_LMO_IMPORT_ERROR_ALLREADY_THIS_PROJECT."</p>";
		$korrekt = 0;
	}
	else {
    echo '<img align="top" src="components/com_joomleague/images/ok.png" alt="O.K." title"O.K.">';
    echo '&nbsp;'; 
    echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_UNIQUE_PROJECT;
    echo '<br /><br />'; 
  }

	if ($korrekt) {	
    //Manage new league creation (could be imported...)
		if ($newLeagueCheck == 1)	{

      if ($_POST['leagueNew']) {
        $newLeague = new League( $database );
        $newLeague->set( 'name', $_POST['leagueNew'] );
        $newLeague->store();
        $proj->set( 'league_id', $newLeague->id );
      } 
			if ($proj->league_id) {
      	echo _JL_ADMIN_EDIT_FORM_LEAGUES_TITLE." <b>$newLeague->name</b> "._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
      }
      else 
        echo _JL_ADMIN_EDIT_FORM_LEAGUES_TITLE." <b>".$_POST['leagueNew']."</b> "._JL_ADMIN_EDIT_LIST_JL_IMPORT_FAILED."<br>"; 
		}
	
    //Manage new season creation (could be imported...)
		if ($newSeasonCheck == 1)	{
      if ($_POST['seasonNew']) {
        $newSeason = new Season( $database );
        $newSeason->set( 'name', $_POST['seasonNew'] );
        $newSeason->store();
        $proj->set( 'season_id', $newSeason->id );
      } 
			if ($proj->season_id)
        echo _JL_ADMIN_EDIT_FORM_SEASONS_TITLE." <b>$newSeason->name</b> "._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
      else
        echo _JL_ADMIN_EDIT_FORM_SEASONS_TITLE." <b>".$_POST['seasonNew']."</b> "._JL_ADMIN_EDIT_LIST_JL_IMPORT_FAILED."<br>";
		}

    //create Project
    $proj->set( 'id' , NULL ); //id as to be reset to be sure to create a new one with store()
    if ( !$proj->store() )
    {
			echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_PROJECT_NOT_CREATED . '<br/>';
			echo $proj->getError();
			exit;    
    }
		else {
      echo _JL_ADMIN_EDIT_LIST_IMPORTS_PROJECT." <b>$proj->name</b> "._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED." (<b>ID  $proj->id)!<br>";
		}
    
    //import template
    if ($_POST['copyTemplate']) {
      $query = "SELECT id FROM #__joomleague_template_config WHERE project_id=".$_POST['copyTemplate'];
		  $database->setQuery($query);
		  $rows = $database->loadObjectList();
		  foreach ($rows AS $row) {
        $template = new TemplateConfig($database);
        $template->load($row->id);
        $template->set( 'project_id', $proj->id );
        $template->set( 'id', NULL );
        $template->store();
      }
    }
    
    //create new clubs
    if(!empty($newclubsid))
		{
			// We have to create these clubs
      foreach ($newclubsid AS $key => $id)
			{
				if ( $id>0 ) { // Try to bind to club from import file
          
          //first, find which club it is among objects
  				foreach ($clubs as $import_club) {
  				  if ( $import_club->id == $id ) break;
          }
          //update club name if user tuned it...
          $import_club->set( 'name' , $newclubs[$key] );
          
          //check that there is not already such a club name in db
          $query = " SELECT id FROM #__joomleague_clubs WHERE name ='$import_club->name'";   
          $database->setQuery($query);
        	$database->query($query);
        	
          if ($database->getAffectedRows()) { 
            //there is already a club with same name, use it.
            $import_club->load( $database->loadResult() );
        		echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_USING_EXISTING_CLUB."<b>$import_club->name ($import_club->id)</b><br/>";
        	}
          else { 
            //Create from imported club
            $import_club->set( 'id' , NULL);            				
    				$import_club->store();
            echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_JL_CLUB." <b>$import_club->name ($import_club->id)</b> "._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br/>";
          }       
        }
        else { // create new club with just the name
          $import_club = new Club ($database);
          $import_club->set( 'name' , $newclubs[$key] );
          $import_club->store();
          echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_JL_CLUB." <b>$import_club->name ($import_club->id)</b> "._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED." (from name)<br>";
        }

        //print_r( $import_club );				
				//keep track of the new club_id
				$convertClubID[$key] = $import_club->id;
			}
		}
		
		//Create new teams	
		if(!empty($newteams))
		{
			echo "<br>";
      // We have to create these teams
      foreach ($newteams AS $key => $value)
			{
				$import_team = $teams[$key];
        
        $import_team->set( 'name' , $value );
        $import_team->set( 'short_name' , $newteamsshort[$key] );
				if (isset($assignedclubs[$key]))
				{
					$import_team->set( 'club_id' , $assignedclubs[$key] );
				}
				else {
          $import_team->set( 'club_id' , $convertClubID[$key] );
        }
				$old_id = $import_team->id;
				$import_team->set( 'id' , NULL);
				$import_team->store();
				
				//keep track of the new team_id
				$convertTeamID[$old_id] = $import_team->id;
				
				if ($import_team->id) {
          echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_JL_TEAM
                ." <b>$import_team->name (ID $import_team->id)</b> "
                ._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
        }
        else {
          echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_JL_TEAM
                ." <b>$value</b> "
                ._JL_ADMIN_EDIT_LIST_JL_IMPORT_FAILED."<br>";
        }
			}
		}
		
		//Update id of assigned teams for tracking
		if(!empty($assignedteams))
		{
      //teams that were replaced with an already existing team
      foreach ($assignedteams AS $key => $value)
			{
				//keep track of the new team_id
  			$convertTeamID[$teams[$key]->id] = $value;
  			//replace object with the one from the database
  			$teams[$key]->load( $value );
  			echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_USING_EXISTING_TEAM
          ." <b>".$teams[$key]->name." (ID ".$teams[$key]->id.")</b><br>";
			}
		}
		//print_r($convertTeamID);
		
		//divisions
		if ( isset($divisions) ) {
  		foreach ( $divisions as $key=>$division) {
  		  $oldId = $division->id;
        $division->set( 'id', NULL );
        $division->set( 'project_id', $proj->id );
        if (!$division->store()) ;//print_r($division);
        
        echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_DIVISION
                  ." <b>$division->name (ID $division->id)</b> "
                  ._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
                  
  		  //keep track of division_id change
        $convertDivisionID[$oldId] = $division->id;
      }
    }
		
    //now create the corresponding teamtoolsid
		foreach ( $teamtools as $key=>$teamtool)
		{
		  $teamtool->set( 'id', NULL );
      $teamtool->set( 'project_id', $proj->id );
		  $teamtool->set( 'team_id', $convertTeamID[$teamtool->team_id] ) ;
		  $teamtool->set( 'division_id', $convertDivisionID[$teamtool->division_id] ) ;
		  $teamtool->store();
		  if ($teamtool->id) {
		    echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_TEAMTOOL
                ." <b>$teamtool->id (for team with id ".$teamtool->team_id.")</b> "
                ._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
      }
      else {
        echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_TEAMTOOL
                ." <b>associated to team ".$teamtool->team_id.")</b> "
                ._JL_ADMIN_EDIT_LIST_JL_IMPORT_FAILED."<br>";
      }
    }
    
  	//Create matchdays
		foreach ( $rounds as $key=>$round)
		{
      $oldId = $round->id;
      $round->set( 'id', NULL ); //to create a new one
      $round->set( 'project_id', $proj->id );
		  $round->store();
		  //keep track of the new round id
  		$convertRoundID[$oldId] = $round->id;
  		if ($round->id) {
		    echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_ROUND
                ." <b>$round->id</b> "
                ._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
      }
      else {
        echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_ROUND
                ." <b> #$key</b> "
                ._JL_ADMIN_EDIT_LIST_JL_IMPORT_FAILED."<br>";
      }
    }
		
		//now, the matches !
		foreach ( $matches as $key=>$match)
		{
		  $match->set( 'match_id', NULL );
		  $match->set( 'project_id', $proj->id );
		  $match->set( 'round_id', $convertRoundID[$match->round_id] );
		  $match->set( 'matchpart1', $convertTeamID[$match->matchpart1] );
		  $match->set( 'matchpart2', $convertTeamID[$match->matchpart2] );
		  $match->store();
		  
		  if ($match->match_id) {
		    echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_MATCH
                ." <b>$match->match_id</b> "
                ._JL_ADMIN_EDIT_LIST_LMO_IMPORT_CREATED."<br>";
      }
      else {
        echo _JL_ADMIN_EDIT_LIST_JL_IMPORT_MATCH
                ." <b> #$key</b> "
                ._JL_ADMIN_EDIT_LIST_JL_IMPORT_FAILED."<br>";
      }
		}
		
    echo "<p>"._JL_ADMIN_EDIT_LIST_JL_IMPORT_SUCCESS."</p>";
	
	}
	else // (!$korrekt)
	{
		   echo '<img align="top" src="components/com_joomleague/images/error.png" alt="Error" title"Error">'; 
       echo '&nbsp;';
       echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_ERROR_NO_SUCCESS;
       echo '<br /><br />';
       echo '<img align="top" src="components/com_joomleague/images/error.png" alt="Error" title"Error">';
       echo '&nbsp;';  		
		   echo _JL_ADMIN_EDIT_LIST_LMO_IMPORT_ERROR_NO_DATABASE_ENTRY;
       echo '<br /><br />';
	}
	echo "</pre>";
}

?>

<!-- JL Import END -->			
			
		</table>
				</div>
<!-- Content End -->	
			
        <div class="clr"></div>
      </div>
      <div class="b">
        <div class="b">
          <div class="b"></div>
        </div>
      </div>
		</div>
	</div>
</div>
<div class="clr"></div>

